﻿using MediatR;
using System.Text.Json;

namespace CQRSLearn.Behaviors
{

    public class RequestResponseLoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : class
    {
        private readonly ILogger<RequestResponseLoggingBehavior<TRequest, TResponse>> logger;

        public RequestResponseLoggingBehavior(ILogger<RequestResponseLoggingBehavior<TRequest, TResponse>> logger)
        {
            this.logger = logger;
        }

        public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
        {
            var correlationId=Guid.NewGuid();
            var requestJson=JsonSerializer.Serialize(request);
            logger.LogInformation($"Handing request {correlationId}:{requestJson}");
            var response = await next();
            var responseJson=JsonSerializer.Serialize(response);
            logger.LogInformation($"Response for {correlationId}:{responseJson}");
            return response;
        }
    }
}
